package com.manager.gen.module;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.manager.commons.utils.DateUtil;
import com.manager.commons.utils.StringUtil;
import com.manager.commons.utils.UUIDUtil;
import com.manager.core.module.manager.entity.PlatformParameter;
import com.manager.core.web.json.AjaxJson;
import com.manager.gen.module.platform.core.service.PublicCommService;
import com.manager.gen.web.controller.AdminController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/comm")
public class PublicController extends AdminController<String> {
    @Autowired
    private PublicCommService _service;
    private final String UPLOAD_PATH = "UPLOAD_PATH";

    /**
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/uploadRes", method = RequestMethod.POST)
    public @ResponseBody AjaxJson uploadRes(@RequestParam(value = "type") String type, @RequestParam(value = "folder") String folder, @RequestParam(value = "file") MultipartFile file) {
        //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp,webp");
        extMap.put("excel", "xls,xlsx");
        try {
            if (file.getSize() > 0) {
                String fileName = file.getOriginalFilename();
                String fileExt = fileName.substring((fileName.lastIndexOf(".") + 1)).toLowerCase();
                if (Arrays.asList(extMap.get(type).split(",")).contains(fileExt)) {
                    PlatformParameter parameter = _service.getBaseParameter(UPLOAD_PATH);
                    String savapath = parameter.getValue_vc() + parameter.getDescription();
                    String saveUrl = "/upload/";
                    if (StringUtils.isNotBlank(folder)) {
                        saveUrl = saveUrl.concat(folder).concat("/");
                    }
                    String path = savapath + saveUrl;
                    File ymdFile = new File(path);
                    if (!ymdFile.exists()) {
                        ymdFile.mkdirs();
                    }
                    String uuid = UUIDUtil.getInstance().getUUID("");
                    String newFileName = uuid + "." + fileExt;
                    file.transferTo(new File(path, newFileName));
                    return new AjaxJson(1, "文件成功", saveUrl + newFileName);
                }
                return new AjaxJson("格式有误！");
            }
            return new AjaxJson("文件为空！");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return new AjaxJson("服务器异常，请稍后再试！");
    }

    /**
     * 文件下载
     */
    @GetMapping("/download")
    public void fileDownload(@PathVariable("fileName") String fileName) {
        if (StringUtil.isNotEmpty(fileName)) {
            String fileN = fileName.substring((fileName.lastIndexOf("/") + 1));
            // 内容类型为通用类型，表示二进制数据流
            String savapath = _service.getBaseParameter(UPLOAD_PATH).getValue_vc();
            inputFileDownload(savapath + fileName, fileN);

        }
    }

    /**
     * 文件下载
     */
    @GetMapping("/{fileName}/template")
    public void templateDownload(@PathVariable("fileName") String fileName) {
        // 文件下载
        // 设置响应头
        String fileN = "";
        if (fileName.endsWith("score")) {
            fileN = "导入成绩数据模版";
        } else if (fileName.endsWith("number")) {
            fileN = "导入编号数据模版";
        }
        PlatformParameter platformParameter = _service.getBaseParameter(UPLOAD_PATH);
        String savapath = platformParameter.getValue_vc() + platformParameter.getDescription().replace("upload/", "");
        inputFileDownload(savapath + "/template/" + fileName + ".xlsx", fileN + ".xlsx");
    }

    private void inputFileDownload(String filePath, String fileName) {
        try {
            File file = ResourceUtils.getFile(filePath);
            fileName = URLEncoder.encode(fileName, "UTF-8");
            //文件名编码，防止中文乱码
            // 设置响应头信息
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            // 内容类型为通用类型，表示二进制数据流
            response.setContentType("application/octet-stream");
            // 循环，边读取边输出，可避免大文件时OOM
            try (InputStream inputStream = Files.newInputStream(file.toPath()); OutputStream os = response.getOutputStream()) {
                byte[] bytes = new byte[1024];
                int readLength;
                while ((readLength = inputStream.read(bytes)) != -1) {
                    os.write(bytes, 0, readLength);
                }
            }
        } catch (Exception e) {

        }
    }

    private String getToJson(List<Map<String, String>> result) {
        Map<String, Object> pMap = getParams();
        if (pMap != null && pMap.containsKey("s")) {
            result.add(0, new HashMap<String, String>() {
                private static final long serialVersionUID = 1144021784068290364L;

                {
                    put("text", "--请选择--");
                    put("value", "");
                }
            });
        }
        return JSON.toJSONString(result);
    }


    @Override
    public String getModel() {
        return null;
    }
}